/**
 * Created by PanJiaChen on 16/11/18.
 */
import _ from 'lodash'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 获取指定日期的周的第一天、月的第一天、季的第一天、年的第一天
 * @param date new Date()形式，或是自定义参数的new Date()
 * @returns 返回值为格式化的日期，yy-mm-dd
 */

// 获取这周的周一
export function getFirstDayOfWeek(date) {
  var weekday = date.getDay() || 7 // 获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7

  date.setDate(date.getDate() - weekday + 1)// 往前算（weekday-1）天，年份、月份会自动变化
  return parseTime(date, '{y}-{m}-{d}')
}

// 获取当月第一天
export function getFirstDayOfMonth(date) {
  date.setDate(1)
  return parseTime(date, '{y}-{m}-{d}')
}

// 获取当季第一天
export function getFirstDayOfSeason(date) {
  var month = date.getMonth()
  if (month < 3) {
    date.setMonth(0)
  } else if (month > 2 && month < 6) {
    date.setMonth(3)
  } else if (month > 5 && month < 9) {
    date.setMonth(6)
  } else if (month > 8 && month < 11) {
    date.setMonth(9)
  }
  date.setDate(1)
  return parseTime(date, '{y}-{m}-{d}')
}

// 获取当年第一天
export function getFirstDayOfYear(date) {
  date.setDate(1)
  date.setMonth(0)
  return parseTime(date, '{y}-{m}-{d}')
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

export function getFileType(filePath, split) {
  var startIndex = filePath.lastIndexOf(split)
  if (startIndex != -1) { return filePath.substring(startIndex + 1, filePath.length).toLowerCase() } else return ''
}
// 生成uuid
export function uuid() {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'
  const uuid = s.join('')
  return uuid
}
/**
 * 数组分组
 * @param {arr,string}
 * @returns {Object}
 */
export function groupBy(arr, param) {
  var groups = {}
  arr.forEach(o => {
    var value = o[param]
    groups[value] = groups[value] || []
    groups[value].push(o)
  })
  var temp = Object.keys(groups).map(i => {
    return groups[i]
  })
  return groups
}
/**
 * 指定属性集合
 * @param {arr,string}
 * @returns {arr}
 */
export function paramList(arr, param, sort = false) {
  const res = arr.map(e => e[param])
  if (sort) {
    res.sort()
  }
  return res
}

/*
* 拼接返回文件名称
*/
export function fileJoinBaseUrl(data) {
  const result = []
  const base = process.env.VUE_APP_BASE_API
  data.forEach(e => {
    const temp = {
      id: e.id,
      fileType: getFileType(e.url, '.'),
      filename: getFileType(e.url, '/'),
      url: base + '/upload/' + e.url
    }
    result.push(temp)
  })
  return result
}
/**
 * 将对象属性值为空的属性过滤
 * @param {Obj}
 * @returns {Object}
 */
export function filterObj(form) {
  const filterForm = {}
  for (const item in form) {
    if (form[item]) {
      filterForm[item] = form[item]
    }
  }
  return filterForm
}

// 跳转到在线office页面
export function previewFile(row, type = 0, pagerId) {
  const { id, fileType, url } = row
  if (['doc', 'docx', 'wps', 'xls', 'xlsx', 'pptx'].includes(fileType)) {
    const { href } = this.$router.resolve({
      name: 'FilePreview',
      query: {
        pagerId: pagerId,
        previewType: type,
        fileId: id
      }
    })
    window.open(href, '_blank')
  } else {
    window.open(url, '_blank')
  }
}
// 跳转到在线office页面2
export function previewFileAppendPath(row, isEdit = 0, isReview = false,isNeedAllUrl = false) {
  const { id, type, url } = row;
  const canPreviewOnlyOffice = [
    "doc",
    "docx",
    "wps",
    "xls",
    "xlsx",
    "pptx",
  ];
  if (
    [
      "pdf",
      "bmp",
      "png",
      "gif",
      "jpeg",
      "jpg",
      "mp4",
      "mp3",
      "json",
      "txt",
      "js",
    ].includes(type)
  ) {
    if(isNeedAllUrl){
      window.open(url,"_blank")
    }else{
      window.open("upload/" + url, "_blank");
    }
    return;
  } else if (canPreviewOnlyOffice.includes(type)) {
    const { href } = this.$router.resolve({
      name: "FilePreview",
      query: {
        previewType: isEdit,
        fileId: id,
        checkedStatus: isReview ? "review" : null,
      },
    });
    window.open(href, "_blank");
  } else {
    this.$message.info(`所选文件暂不支持在线预览`);
  }
}

/**
 * 将JSON数组行列转换
 * @param {*} list 原始数据
 * @param {*} exportColumns 初始表头
 * @returns 
 */
export const rowToColumnOfJsonData = (groupData, exportColumns = []) => {
  if (!groupData) {
    throw new Error('This Method need Array!')
  }
  const result = []
  const columns = []
  let maxCount = 0
  Object.keys(groupData).forEach(key => {
    // 获取第一行数据值作为表格列
    columns.push(key)
    // 计算列表最大深度
    const length = groupData[key].length
    if (length > maxCount) {
      maxCount = length
    }
  })
  // 按日期排序
  columns.sort()
  // 遍历对象，根据最大深度创建记录，
  // 以日期作为键, 最大深度索引获取对应值；如果没有则为空
  for (let index = 0; index <= maxCount; index++) {
    const record = []
    for (let colIndex = 0; colIndex < columns.length; colIndex++) {
      const col = columns[colIndex];
      const list = groupData[col]
      const { content, username } = list[index] || {}
      record.push(list[index] ? `${username}：\n${content}` : '')
    }
    result.push(record)
  }

  return {
    tableHeader: columns,
    tableData: result
  }
}

/**
     * 导出excel
     * js-export-excel组件体积过大，暂时使用xlsx代替
     */
export const exportExcel = (dataSource = [], tableHeader = [], needId = false, fileName = '日程') => {
  // const data = [...dataSource]
  // let option = {}
  // let dataTable = []
  // let sheetHeader = []
  // //生成表头
  // if(tableHeader.length) {
  //   sheetHeader = tableHeader
  // } else {
  //   for (let index in data[0]) {
  //     if (!needId && index === 'id') continue
  //     sheetHeader.push(index)
  //   }
  // }
  // //生成表内容
  // for (let index in data) {
  //   const item = {}
  //   for (let key in data[index]) {
  //         item[key] = data[index][key]
  //     }
  //     dataTable.push(item)
  // }
  // //表名
  // option.fileName = fileName
  // option.datas = [
  //     {
  //         sheetData: dataTable,
  //         sheetName: 'sheet',
  //         sheetFilter: sheetHeader,
  //         sheetHeader: sheetHeader,
  //         columnWidths: new Array(sheetHeader.length).fill(8)
  //     }
  // ]
  // const toExcel = new CreateExcel(option);
  // toExcel.saveExcel()
}

/**
 * 对比原始数组和当前数组区别
 * @param {*} origin 
 * @param {*} target 
 * @returns 
 */
export function matchOriginArrayDiffence(origin = [], target = []) {
  const newRecords = []
  const savedRecords = []
  // 改动过的项
  const updateSet = _.differenceWith(target, origin, _.isEqual);
  updateSet.forEach(item => {
    // 新增项 status有值
    if (item.tempID) {
      newRecords.push(item)
      // 修改项
    } else {
      savedRecords.push(item)
    }
  })
  return { newRecords, savedRecords }
}

/**
 * 将base64转换为file对象
 */
export function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

/**
 * 下载二进制文件
 * @param {*} data 
 */
export function downloadBinaryFile(data) {
  if (!data) {
    return
  }
  let url = window.URL.createObjectURL(new Blob([data]))
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click();
  link.remove();
}

/**
  * 输入指定日期，返回日期所在周的所有日期数组
  */
export function getWeekDays(input_day = "") {
  if (!input_day) return [];
  let oneDayTime = 1000 * 60 * 60 * 24;
  let today = new Date(input_day);
  // 若那一天是周末时，则强制赋值为7
  let todayDay = today.getDay() || 7;
  let startDate = new Date(today.getTime() - oneDayTime * (todayDay - 1));
  let dateList = new Array();
  for (let i = 0; i < 7; i++) {
    let temp = new Date(startDate.getTime() + i * oneDayTime);
    let year = temp.getFullYear();
    let month = temp.getMonth() + 1;
    let day = temp.getDate();
    const _month = month < 10 ? "0" + month : month;
    const _day = day < 10 ? "0" + day : day;
    dateList[i] = `${year}-${_month}-${_day}`;
  }
  return dateList;
}